package com.zhouyu.proxy;


import com.zhouyu.service.UserService;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.context.annotation.Bean;

public class ProxyConfig {

	@Bean
	public ProxyFactoryBean userServiceProxy(){
		UserService target = new UserService();
		ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
		proxyFactoryBean.setTarget(target);
		proxyFactoryBean.setProxyTargetClass(true);
		proxyFactoryBean.addAdvice(new MethodInterceptor() {
			@Nullable
			@Override
			public Object invoke(@NotNull MethodInvocation invocation) throws Throwable {
				System.out.println("Before method: " + invocation.getMethod().getName());
				Object result = invocation.proceed();
				System.out.println("After method: " + invocation.getMethod().getName());
				return result;
			}
		});
		return proxyFactoryBean;
	}

	@Bean
	public ProxyFactoryBean userServiceProxy2(){
		UserService target = new UserService();
		ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
		proxyFactoryBean.setTarget(target);
		proxyFactoryBean.setProxyTargetClass(true);
		proxyFactoryBean.setInterceptorNames("methodInterceptor");
		return proxyFactoryBean;
	}

	@Bean
	public MethodInterceptor methodInterceptor(){
		return new MethodInterceptor(){

			@Nullable
			@Override
			public Object invoke(@NotNull MethodInvocation invocation) throws Throwable {
				System.out.println("Before method: " + invocation.getMethod().getName());
				Object result = invocation.proceed();
				System.out.println("After method: " + invocation.getMethod().getName());
				return result;
			}
		};
	}

}
